package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock{

    private static final String KEY_PREFIX = "lock:";
    //使用UUID区分不同的进程(JVM)
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;//释放锁的lua脚本

    static {//加载类时初始化lua脚本，而不是每次调用unlock方法时初始化lua脚本，这样性能更好
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));//配置路径
        UNLOCK_SCRIPT.setResultType(Long.class);//设置返回类型
    }


    private StringRedisTemplate redisTemplate;
    private String name;

    public SimpleRedisLock(StringRedisTemplate redisTemplate, String name) {
        this.redisTemplate = redisTemplate;
        this.name = name;
    }

    /**
     * 尝试获取锁
     * @param timeoutSec 锁超时时间，过期自动释放
     * @return true 获取锁成功  false获取锁失败
     */
    @Override
    public boolean tryLock(long timeoutSec) {
        //获取线程标识
        //使用UUID区分不同的进程(JVM)  使用threadId区分同一进程内的不同线程
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        //尝试获取锁
        Boolean success = redisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, threadId, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    /**
     * 释放锁
     */
//    @Override
//    public void unlock() {
//        //获取线程标识
//        String threadId = redisTemplate.opsForValue().get(KEY_PREFIX + name);
//        //判断线程标识是否和自己的一致，即判断是否为自己的锁，防止误删别的线程的锁
//        if (threadId == null || !threadId.equals(ID_PREFIX + Thread.currentThread().getId())) {
//            return;
//        }
//        redisTemplate.delete(KEY_PREFIX + name);
//    }
    @Override
    public void unlock() {
        ArrayList<String> keys = new ArrayList<>();
        keys.add(KEY_PREFIX + name);
        redisTemplate.execute(UNLOCK_SCRIPT, keys, ID_PREFIX + Thread.currentThread().getId());
    }
}
